package node.exp;

import grammar.Lexer;
import lexical.Key;
import node.Node;
import node.block.stmt.IfStmt;
import node.block.stmt.WhileStmt;
import symbol.SymbolTable;

import java.util.ArrayList;

public class LOrExp implements Node {
    private final Lexer lexer;
    private final SymbolTable table;
    private final Node father;
    private boolean whileCond = false;
    private boolean needOp = false;
    private ArrayList<LAndExp> landExps = new ArrayList<>();

    public LOrExp(Lexer lexer, SymbolTable table, Node father) {
        this.lexer = lexer;
        this.table = table;
        this.father = father;
        parseLOrExp();
    }

    private void parseLOrExp() {
        landExps.add(new LAndExp(lexer, table, this));
        while (lexer.isWordType(0, Key.OR)) {
            lexer.getCurWord(); // ||
            landExps.add(new LAndExp(lexer, table, this));
        }
    }

    public int getLAndNum() {
        return landExps.size();
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(landExps.get(0).toString());
        for (int i = 1; i < landExps.size(); i++) {
            sb.append("OR ||\n").append(landExps.get(i).toString()).append("<LOrExp>\n");
        }
        return sb.toString();
    }

    @Override
    public String genMidCode() {
        Node node = father.getFather();
        String notLastLabel = "";
        String lastLabel = "";
        if (node instanceof IfStmt) { // ifStmt
            notLastLabel = ((IfStmt)node).getLabel1();
            lastLabel = ((IfStmt)node).getLabel2();
        } else if (node instanceof WhileStmt) { // whileStmt
            whileCond = true;
            notLastLabel = ((WhileStmt)node).getLabel2();
            lastLabel = ((WhileStmt)node).getLabel3();
        }
        if (!needOp) {
            for (int i = 0;i < landExps.size();i++) {
                if (i == landExps.size() - 1) {
                    landExps.get(i).genMidCode(true,lastLabel, null);
                } else {
                    landExps.get(i).genMidCode(false,notLastLabel, null);
                }
            }
        } else {
            for (int i = 0; i < landExps.size(); i++) {
                if (i == landExps.size() - 1) {
                    landExps.get(i).genMidCode(true, lastLabel, notLastLabel);
                } else {
                    landExps.get(i).genMidCode(false, notLastLabel, null);
                }
            }
        }
        if (whileCond) {
            needOp = true;
        }
        return "";
    }
}

